function [Tq Pq] = qntl (x, binn, QP, nb, verbose)

   ## usage: [Tq Pq] = qntl (x, binn, QP, nb, verbose)
   ## 
   ## estimate quantiles

   if nargin < 4, nb = 20 ; endif
   if nargin < 5, verbose = false ; endif

   ## choose binning
   if strcmp(binn, "T")
      Tb = linspace(min(x(:,1)), max(x(:,1)), nb) ;
   else
      Tb = quantile(x(:,1), linspace(0, 1, nb+1))' ;
   endif

   ## pkg unload optim ; opt = struct("method", "mps") ;
   ## phat = fitgam(x(:,2), opt) ;

   j = 0 ; Pq = Prq = [] ; Pq = nan(length(Tb)-1, length(QP)) ;
   for t=Tb(2:end)
      j++ ; Tq(j,1) = mean(Tb(j:j+1)) ;
      I = (Tb(j) <= x(:,1) & x(:,1) <= Tb(j+1)) ; 
      J = sum(I) > 1./(1-QP) ;
      if any(J)
	 Pq(j,J) = quantile(x(I,2), QP(J))' ;
      endif

      ## Prq(j,:) = qntrnd(x(I,2), phat, 100) ;
      ## ## Pq(j,:) = mean(x(I,2)) ;
      ## printf("%3d %4.1f (%d): %4.1f %4.1f %4.1f %4.1f\n", j, Tq(j), sum(I), [Pq(j,:) ; Prq(j,:)]) ;
      if verbose
	 printf(["%3d %4.1f (%d):" repmat(" %7.3g", 1, length(QP)) "\n"], j, Tq(j,1), sum(I), Pq(j,:)) ;
      endif
   endfor

endfunction
